package zhoug.demo.common.fileselector;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;

import java.io.File;
import java.util.List;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import zhoug.common.camera.ui.CaptureImageActivity;
import zhoug.common.clip.ClipImageHelper;
import zhoug.common.clip.IClipImageHelper;
import zhoug.common.clip.OnImageClipResultListener;
import zhoug.common.clip.SystemClipImageHelper;
import zhoug.common.fileselector.FilePreview;
import zhoug.common.fileselector.FileSelectorHelper;
import zhoug.common.fileselector.beans.LocalMedia;
import zhoug.common.fileselector.selector.FileSelectedConfig;
import zhoug.common.fileselector.selector.FileSelector;
import zhoug.common.fileselector.selector.FileSelectorBuilder;
import zhoug.common.fileselector.selector.FileSelectorDialog;
import zhoug.common.fileselector.selector.IFileSelector;
import zhoug.common.fileselector.selector.OnCaptureClick;
import zhoug.common.permission.ZPermissions;
import zhoug.common.utils.AppUtils;
import zhoug.common.utils.FileUtils;
import zhoug.common.utils.TimeUtils;
import zhoug.common.utils.UriUtils;
import zhoug.demo.common.MyBaseActivity;
import zhoug.demo.common.R;
import zhoug.logging.Logger;

/**
 * 测试文件选择器
 *
 * @Author: zhoug
 * @Date: 2025-02-08
 * @Description:
 */
public class TestFileSelectorActivity extends MyBaseActivity {
    private static final String TAG = ">>>TestFileSelectorActivit";
    private ActivityResultLauncher<Intent> mCaptureImgLauncher;
    private IFileSelector mIFileSelector;
    private IFileSelector mImageSelector;
    private IClipImageHelper iClipImageHelper;
    private ClipImageHelper mClipImageHelper;
    private SystemClipImageHelper mSystemClipImageHelper;
    private FileSelectorDialog mFileSelectorDialog;
    private String mOutDataPath;

    private Button mBtn1;
    private Button mBtn2;
    private TextView mTvResult;
    private FilePreview mFilePreview;
    private Button mBtnImage;
    private Switch mSwitchCrop;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_test_file_selector;
    }

    @Override
    protected void findViews() {

        mBtn1 = findViewById(R.id.btn1);
        mBtn2 = findViewById(R.id.btn2);
        mTvResult = findViewById(R.id.tv_result);
        mFilePreview = findViewById(R.id.filePreview);
        mBtnImage = findViewById(R.id.btn_image);
        mSwitchCrop = findViewById(R.id.switch_crop);
    }

    @Override
    protected void onCreate1(Bundle savedInstanceState) {
        getLifecycle().addObserver(new DefaultLifecycleObserver() {
            @Override
            public void onCreate(@NonNull LifecycleOwner owner) {
                mCaptureImgLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result != null && result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                            Intent data = result.getData();
                            Uri uri = data.getData();
                            if (uri != null) {
                                String path = UriUtils.getPathFromUri(getActivity(), uri);
                                Logger.d(TAG, "自定义拍照 path:" + path);
                            }
                        }
                    }
                });
            }

            @Override
            public void onDestroy(@NonNull LifecycleOwner owner) {
                mCaptureImgLauncher.unregister();
            }
        });


        FileSelectorHelper.setOnCaptureClick(new OnCaptureClick() {
            @Override
            public boolean image() {

                return true;
            }

            @Override
            public boolean audio() {
                return false;
            }

            @Override
            public boolean video() {
                return false;
            }

            @Override
            public void captureImage(Activity activity, int requestCode, String path) {
                Intent imageIntent = new Intent(getActivity(), CaptureImageActivity.class);
                imageIntent.putExtra(CaptureImageActivity.EXTRA_PATH, path);
                imageIntent.putExtra(CaptureImageActivity.EXTRA_PIC_WIDTH, 1080);
                imageIntent.putExtra(CaptureImageActivity.EXTRA_PIC_HEIGHT, 1920);
                mCaptureImgLauncher.launch(imageIntent);
            }

            @Override
            public void captureVideo(Activity activity, int requestCode, String path) {

            }

            @Override
            public void captureAudio(Activity activity, int requestCode, String path) {

            }
        });


        mFilePreview.setDeleteEnable(true);
        FileSelectorBuilder builder = new FileSelectorBuilder(this);
        mIFileSelector = builder.captureAll(true)
                .compressImage(true)
                .captureAudio(true)
                .captureVideo(true)
                .captureImage(true)
                .singleModel(false)
                .setMaxNum(5)
                .setOnSelectListener((FileSelector.onSelectListener) this::onSelectFileResult)
                .build();


        mBtn1.setOnClickListener(v -> {
            ZPermissions.with(this)
                    .setPermissions(Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .setCallback((success, granted, denied) -> {
                        if (success) {
                            mIFileSelector.show();
                        }
                    })
                    .request();

        });

        mClipImageHelper = ClipImageHelper.with(this);
        mClipImageHelper.setOnImageClipResultListener(onImageClipResultListener)
                .setFrameRatio(1.35f);


        mSystemClipImageHelper = SystemClipImageHelper.with(this);
        mSystemClipImageHelper.setOnImageClipResultListener(onImageClipResultListener)
                .setAspect(3, 4)
                .setOutputX(300, 400)
        ;

        mImageSelector = new FileSelectorBuilder(this).captureAll(true)
                .compressImage(true)
                .setFlag(FileSelector.FLAG_IMAGE)
                .captureAudio(true)
                .captureVideo(true)
                .captureImage(true)
                .singleModel(true)
                .setMaxNum(1)
                .setOnSelectListener(new FileSelector.onSelectListener() {
                    @Override
                    public void onResult(List<LocalMedia> medias) {
                        if (medias != null && medias.size() == 1) {
                            String inputPath = medias.get(0).getPath();
                            File crop = FileUtils.getExternalPublicFolder(Environment.DIRECTORY_PICTURES);
//                            File crop = FileUtils.getCacheDir(getActivity());
//                            File crop= FileUtils.getAppExternalFilesDir(getActivity(),Environment.DIRECTORY_PICTURES);
                            File file = new File(crop, TimeUtils.getCurrentTime("yyyyMMdd_HHmmss") + ".jpg");
                            mOutDataPath = file.getPath();
                            if (mSwitchCrop.isChecked()) {
                                iClipImageHelper = mClipImageHelper;
                            } else {
                                iClipImageHelper = mSystemClipImageHelper;
                            }
                            iClipImageHelper.setInputData(UriUtils.getUriForFile(getActivity(), inputPath));
                            iClipImageHelper.setOutputData(UriUtils.getUriForFile(getActivity(), mOutDataPath));
                            iClipImageHelper.start();
                        }
                    }
                })
                .build();
        mBtnImage.setOnClickListener(v -> {
            ZPermissions.with(this)
                    .setPermissions(Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .setCallback((success, granted, denied) -> {
                        if (success) {
                            mImageSelector.show();
                        }
                    })
                    .request();

        });

        mFileSelectorDialog = new FileSelectorDialog(this);
        FileSelectedConfig fileSelectedConfig = mFileSelectorDialog.getFileSelectedConfig();
        fileSelectedConfig.captureAudio = true;
        fileSelectedConfig.captureImage = true;
        fileSelectedConfig.captureVideo = true;
        mFileSelectorDialog.setOnSelectListener((FileSelector.onSelectListener) this::onSelectFileResult);
        mBtn2.setOnClickListener(v -> {
            mFileSelectorDialog.show();

        });
    }

    private void onSelectFileResult(List<LocalMedia> medias) {
        if (medias != null && !medias.isEmpty()) {
            StringBuilder stringBuilder = new StringBuilder();
            for (LocalMedia item : medias) {
                stringBuilder.append(item.getPath());
                stringBuilder.append("\n");
            }
            mTvResult.setText(stringBuilder.toString());
            mFilePreview.addFiles(medias);
        } else {
            mTvResult.setText(null);
            mFilePreview.addFiles(null);
        }
    }


    private OnImageClipResultListener onImageClipResultListener = new OnImageClipResultListener() {
        @Override
        public void onImageClipResult(boolean success) {
            Logger.d(TAG, "onImageClipResult:success=" + success);
            Logger.d(TAG, "onImageClipResult:mOutDataPath=" + mOutDataPath);
            if(!success){
                toast("裁剪失败");
                return;
            }
            File file = new File(mOutDataPath);
            if (!file.exists()) {
                toast("mOutDataPath 文件不存在");
                return;
            }
            AppUtils.scannerFile(getActivity(), file);
            mTvResult.setText(mOutDataPath);
            mFilePreview.addFile(new LocalMedia(mOutDataPath));
            mOutDataPath = null;
        }
    };


   /* @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mIFileSelector != null) {
            mIFileSelector.onActivityResult(requestCode, resultCode, data);
        }
        if (mFileSelectorDialog != null) {
            mFileSelectorDialog.onActivityResult(requestCode, resultCode, data);
        }
    }*/

}
